<?php
declare (strict_types=1);

namespace app\admin\listener;

use think\Request;
use think\Response;
use Jenssegers\Agent\Agent;
use app\common\enum\SystemEnum;
use app\common\utils\IpInfoUtils;
use app\common\model\system\UserLogModel;

class HttpEnd
{
    /**
     * 事件监听处理
     * http请求结束后开始记录日志操作
     * @param Response $response
     * @param Request $request
     * @return void
     */
    public function handle(Response $response, Request $request): void
    {
        $return_data = $response->getData();
        if (empty($return_data) || $return_data['code'] === SystemEnum::ROUTE_MISS) {
            return;//如果访问命中MISS路由不记录日志
        }
        if (get_sys_config('site_log') === 'false') {
            return;//如果关闭了日志记录则停止
        }
        $token_info = $request->token_info;
        if (empty($token_info)) {
            return;//未登录的接口不记录日志
        }
        $cache_user_info = $request->cache_user_info;//获取用户登录后的缓存数据
        //开始组装要写入日志的数据
        $ip_info                        = IpInfoUtils::getInfo();
        $agent_info                     = new Agent();
        $agent_browser                  = $agent_info->browser();
        $agent_browser_version          = $agent_info->version($agent_browser);
        $agent_platform                 = $agent_info->platform();
        $agent_platform_version         = $agent_info->version($agent_platform);
        $agent_user_agent               = $agent_info->getUserAgent();
        $log['system_user_id']          = $cache_user_info['id'];
        $log['system_user_account']     = $cache_user_info['account'];
        $log['system_menu_after_route'] = $request->baseUrl();
        $log['request_method']          = $request->method();
        $log['request_ip']              = $ip_info['ip'];
        $log['request_country']         = $ip_info['country'];
        $log['request_province']        = $ip_info['province'];
        $log['request_city']            = $ip_info['city'];
        $log['request_region']          = $ip_info['region'];
        $log['request_isp']             = $ip_info['isp'];
        $log['request_os']              = $agent_platform . '_' . $agent_platform_version;
        $log['request_browser']         = $agent_browser . '_' . $agent_browser_version;
        $log['request_user_agent']      = $agent_user_agent;
        $log['request_data']            = $request->param();
        $log['response_code']           = $return_data['code'];
        $log['response_message']        = $return_data['message'];
        //$log['response_data']           = empty($return_data['data']) ? [] : $return_data['data'];//数据可能太大,暂时不记录返回的数据,后期放到log日志文件内记录
        //开始写入数据
        UserLogModel::create($log);
        //$log_model = new UserLogModel();
        //$log_model->add($log);
    }
}
